//#ifndef instream_js
//#define instream_js 1

//#include "decode.js"

// Used to read values represented by a user specified number of bits from 
// a 'bytestream' array.

function InStream (encoded) {
  var a = encoded.split('!');
  this.bitcount = decode.toNumber(a[0]);
  this.bytestream = decode.toArray(a[1]);
  this.offset = 0;
}

InStream.prototype = {

  ReadBit : function() {
    var b = this.bytestream[this.offset>>>3] >> (this.offset & 7);
    this.offset++;
    return b&1;
  },

  Read : function(numBits) {
    if((this.offset + numBits) > this.bitcount) return null;
    // Read LSB -> MSB
    for(var i=0, v=0; i < numBits; ++i) {
      v |= this.ReadBit() << i;
    }
    return v;
  }
  
};

//#endif

